<template>
  <div class="register-form-container">
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-position="top"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入4-20位字母、数字或下划线"
          clearable
          @blur="checkUsernameExist"
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          placeholder="请输入6-20位密码"
          show-password
          type="password"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          placeholder="请再次输入密码"
          show-password
          type="password"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="registerForm.nickname"
          placeholder="请输入昵称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          clearable
          @blur="checkEmailExist"
        >
          <template #append>
            <el-button
              :disabled="isSending || !registerForm.email"
              @click="handleSendCode"
            >
              {{ codeButtonText }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="验证码" prop="verifyCode">
        <el-input
          v-model="registerForm.verifyCode"
          placeholder="请输入邮箱验证码"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="角色" prop="roleCode">
        <el-radio-group v-model="registerForm.roleCode">
          <el-radio label="INITIATOR">发起人</el-radio>
          <el-radio label="CONTESTANT">参赛者</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item class="register-btn-container">
        <el-button type="primary" round :loading="loading" @click="handleRegister">
          立即注册
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { register, sendEmailCode, checkUsername, checkEmail } from '@/api/user'

export default {
  name: 'RegisterForm',
  emits: ['register-success'],
  setup(props, { emit }) {
    const registerFormRef = ref(null)
    const loading = ref(false)
    const isSending = ref(false)
    const countdown = ref(0)
    
    // 验证码按钮文字
    const codeButtonText = computed(() => {
      return isSending.value ? `${countdown.value}秒后重新获取` : '获取验证码'
    })
    
    // 注册表单
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      nickname: '',
      email: '',
      verifyCode: '',
      roleCode: 'CONTESTANT' // 默认选择参赛者角色
    })
    
    // 自定义校验规则
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度必须在6-20个字符之间'))
      } else {
        if (registerForm.confirmPassword !== '') {
          registerFormRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    // 表单校验规则
    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 4, max: 20, message: '用户名长度必须在4-20个字符之间', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
      ],
      password: [
        { validator: validatePassword, trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ],
      roleCode: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }
    
    // 检查用户名是否已存在
    const checkUsernameExist = async () => {
      if (!registerForm.username || registerForm.username.length < 4) return
      
      try {
        const res = await checkUsername(registerForm.username)
        if (res.data) {
          ElMessage.warning('该用户名已被注册')
          registerForm.username = ''
        }
      } catch (error) {
        console.error('检查用户名失败', error)
      }
    }
    
    // 检查邮箱是否已存在
    const checkEmailExist = async () => {
      if (!registerForm.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) return
      
      try {
        const res = await checkEmail(registerForm.email)
        if (res.data) {
          ElMessage.warning('该邮箱已被注册')
          registerForm.email = ''
        }
      } catch (error) {
        console.error('检查邮箱失败', error)
      }
    }
    
    // 处理发送验证码
    const handleSendCode = async () => {
      if (!registerForm.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
        ElMessage.warning('请输入正确的邮箱格式')
        return
      }
      
      isSending.value = true
      countdown.value = 60
      
      try {
        await sendEmailCode({ email: registerForm.email })
        ElMessage.success('验证码已发送到您的邮箱，请查收')
        
        // 开始倒计时
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
            isSending.value = false
          }
        }, 1000)
      } catch (error) {
        console.error('发送验证码失败', error)
        isSending.value = false
      }
    }
    
    // 处理注册
    const handleRegister = () => {
      registerFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const params = {
              username: registerForm.username,
              password: registerForm.password,
              nickname: registerForm.nickname,
              email: registerForm.email,
              verifyCode: registerForm.verifyCode,
              roleCode: registerForm.roleCode
            }
            
            await register(params)
            ElMessage.success('注册成功')
            emit('register-success')
            
            // 重置表单
            registerFormRef.value.resetFields()
          } catch (error) {
            console.error('注册失败', error)
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      isSending,
      codeButtonText,
      checkUsernameExist,
      checkEmailExist,
      handleSendCode,
      handleRegister
    }
  }
}
</script>

<style lang="scss" scoped>
.register-form-container {
  .el-form-item {
    margin-bottom: 16px;
    
    :deep(.el-form-item__label) {
      padding-bottom: 4px;
      font-size: 14px;
    }
  }
  
  .register-btn-container {
    margin-top: 20px;
    
    .el-button {
      width: 100%;
      height: 42px;
      font-size: 16px;
      background: linear-gradient(135deg, #3a7bd5, #00d2ff);
      border: none;
      
      &:hover, &:focus {
        background: linear-gradient(135deg, #2d62ab, #00b8e6);
      }
    }
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 0 0 1px #e2e8f0;
    
    &.is-focus {
      box-shadow: 0 0 0 1px #3a7bd5;
    }
  }
  
  :deep(.el-input-group__append) {
    padding: 0;
    
    button {
      border: none;
      height: 32px;
      padding: 0 10px;
      border-radius: 0 8px 8px 0;
      background-color: #3a7bd5;
      color: #fff;
      
      &:hover {
        background-color: #2d62ab;
      }
      
      &:disabled {
        background-color: #a0aec0;
        cursor: not-allowed;
      }
    }
  }
  
  :deep(.el-radio__label) {
    font-size: 14px;
  }
  
  :deep(.el-radio__input.is-checked .el-radio__inner) {
    border-color: #3a7bd5;
    background: #3a7bd5;
  }
  
  :deep(.el-radio__input.is-checked+.el-radio__label) {
    color: #3a7bd5;
  }
}
</style> 